package com.luke.netty.sample;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * @Descrtption NettyClient
 * @Author luke
 * @Date 2020/4/29
 **/
public class NettyClient {

    private static final int LISTEN_PORT = 8765;

    public static void main(String[] args) {
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();//客户端使用的是Bootstrap
        bootstrap.group(eventLoopGroup)//只需要一个线程池
                .channel(NioSocketChannel.class)//Channel是实现类型是SocketChannel
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        //获取管道
                        ChannelPipeline pipeline = ch.pipeline();
                        //往管道添加自定义的通道处理器
                        pipeline.addLast(new NettyClientChannelHandler());
                    }
                });

        try {
            //客户端连接服务器端
            ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", LISTEN_PORT).sync();
            System.out.println("客户端连接成功");

            //监听客户端关闭连接
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            eventLoopGroup.shutdownGracefully();
        }

    }

}
